package com.itkaige.boot.controller;

import com.itkaige.boot.mapper.ProductMapper;
import com.itkaige.boot.pojo.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

@Controller
public class ProController {

    @Autowired
    ProductMapper productMapper;

    @RequestMapping("/products/select")
    public String selectAll(Model model) {
        List<Product> productList = new LinkedList<>();
        productList = productMapper.selectAll();
        model.addAttribute("allProducts", productList);
        return "list";
    }

        @RequestMapping("/products/add")
    public String add(HttpServletRequest request, Model model){
        String name=request.getParameter("name");
        String gloryPower=request.getParameter("gloryPower");
//        *********************从前端form表单获取数据*****************************
        productMapper.addPro(new Product(null,name,gloryPower));
        return "redirect:/products/select";
    }

    @RequestMapping("/products/{id}")
//    ***************************从前端列表获取要编辑修改的位置id (Product对象的属性id)**********************
    public String updateGetId(@PathVariable("id") int id, Model model){
        Product product=productMapper.selectById(id);
        model.addAttribute("updatePro",product);
//        *********************向前端传送数据*****************************

        return "update";
    }

    @RequestMapping("products/update/{id}")
    public String updatePro(@PathVariable("id") int id, HttpServletRequest request){
        productMapper.updatePro(new Product(id,request.getParameter("name"),request.getParameter("gloryPower")));
        return "redirect:/products/select";
    }

    @RequestMapping("products/delete/{id}")
    public String delete(@PathVariable("id") int id){
        productMapper.deletePro(id);
        return "redirect:/products/select";
    }
}
